package com.sxf.auth.attach;

import cn.hutool.core.date.DateUtil;
import com.sxf.common.exceptions.BusinessException;
import com.sxf.consts.Consts;
import com.sxf.consts.YtConsts;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

/**
 * @author liu.chunhui
 * @version 1.0
 * @description
 * @date 2024/4/15 22:36:21
 */
@Service
public class AttachService {
    private static final Logger logger = LoggerFactory.getLogger(AttachService.class);
    @Value("${sxf.file.store.path.bank:/data/file/bank/}")
    private String fileStorePath;
    @Value("${sxf.file.store.url:}")
    private String fileStoreUrl;

    public String uploadFile(MultipartFile file){
        if (Objects.isNull(file) || file.getSize() == 0) {
            throw new BusinessException("未收到所传文件或者所传文件大小为0");
        }

        // 2.获取后缀
        String suffix = "";
        logger.info("原文件名为{}", file.getOriginalFilename());
        if (file.getOriginalFilename().indexOf(".") > -1) {
            suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        } else {
            suffix = Optional.ofNullable(file.getOriginalFilename()).orElse("");
        }

        // 3.校验后缀
        if (!YtConsts.ALLOW_FILE.contains(suffix.toLowerCase())) {
            throw new BusinessException(file.getOriginalFilename() + "该文件类型不允许上传！");
        }
        String fileDiskPath = saveFile(file,suffix);
        return fileDiskPath;
    }

    private String saveFile(MultipartFile file,String suffix) {
        String dataStr = DateUtil.format(new Date(), Consts.DATE_PATTERN);
        String fileName =  getUuid(suffix);
        String filepath = getFilePath(dataStr) + fileName;
        try{
            File dir = new File(getFilePath(dataStr));
            if(!dir.exists()){
                dir.mkdirs();
            }
            File temp = new File(filepath);
            if (!temp.exists()) {
                temp.createNewFile();
            }
            FileUtils.copyInputStreamToFile(file.getInputStream(), temp);
        }catch (IOException e){
            logger.error("保存文件至本地失败",filepath,e);
            throw new BusinessException("银行卡保存失败");
        }

        if(isWindows()){
            return fileStoreUrl  + dataStr + "\\"+ fileName;
        }else {
            return fileStoreUrl + dataStr + "/" + fileName;
        }
    }
    private String getUuid(String suffix){
        return UUID.randomUUID().toString().replace("-", "").toUpperCase() + "." + suffix;
    }
    private String getFilePath(String dataStr){
        if(isWindows()){
            return "D:\\data\\file\\" + dataStr + "\\";
        } else {
            return fileStorePath + dataStr + "/";
        }
    }
    private boolean isWindows() {
        return System.getProperty("os.name").toLowerCase().contains("windows");
    }



}
